package com.shoplink.launcher;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

public class NetworkSettingsActivity extends Activity {
	private WifiSettingFragment wifiFragment;
	private EthSettings ethFragment;
	private IntentFilter mNetworkFilter;
	private View wifiApDetails;
	private ImageView icoTitle;
	// private EthernetManager mEthManager; // cqd add
	private static final String TAG = NetworkSettingsActivity.class
			.getSimpleName();

	private final int NET_WORK_STATE_CHANGE_MSG = 191;
	private FragmentTransaction transaction;
	@Override
	protected void onCreate(Bundle saveInstanceState) {
		super.onCreate(saveInstanceState);
		setContentView(R.layout.network_settings);
		changeWindowMode(0);
		boolean isEthernet = checkEthernet(getApplicationContext());
		Log.d("network", "is ethernet : " + isEthernet);

		wifiFragment = new WifiSettingFragment();
		ethFragment = new EthSettings();
		icoTitle = (ImageView) findViewById(R.id.ico_title);
		wifiApDetails = findViewById(R.id.wifi_ap_details);
		mNetworkFilter = new IntentFilter();
		mNetworkFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		mNetworkFilter.addAction(ConnectivityManager.INET_CONDITION_ACTION);
		mNetworkFilter
				.addAction(ConnectivityManager.ACTION_TETHER_STATE_CHANGED);
		registerReceiver(networkReceiver, mNetworkFilter);
		updateFragment();
	}

	BroadcastReceiver networkReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, final Intent intent) {
			Log.d("netWork", "===>" + intent.getAction());
			if (intent.getAction().equals(
					ConnectivityManager.CONNECTIVITY_ACTION)) {
				handler.removeMessages(NET_WORK_STATE_CHANGE_MSG);
				handler.sendEmptyMessageDelayed(NET_WORK_STATE_CHANGE_MSG, 1000);
			}
		}
	};

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			if (msg.what == NET_WORK_STATE_CHANGE_MSG) {
				updateFragment();
			}

		};
	};

	public static boolean checkEthernet(Context context) {
		ConnectivityManager conn = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = conn
				.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
		return networkInfo.isConnected();
	}

	public void changeWindowMode(int type) {
		if (type == 0) {
			getWindow().setSoftInputMode(
					WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
		} else {
			getWindow()
					.setSoftInputMode(
							WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
									| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		}
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		try {
			transaction.remove(ethFragment);
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			transaction.remove(wifiFragment);
		} catch (Exception e) {
			// TODO: handle exception
		}
		this.finish();
		super.onStop();
	}

	private void updateFragment() {

		if (wifiApDetails != null) {
			  transaction = this.getFragmentManager()
					.beginTransaction();
			ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo activeInfo = manager.getActiveNetworkInfo();
			NetworkInfo ethInfo = manager
					.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
			icoTitle.setImageResource(R.drawable.ico_title_wifi);

			transaction.remove(wifiFragment);
			transaction.replace(R.id.wifi_ap_details, wifiFragment);
			Log.d(TAG, "activeInfo:" + activeInfo);

			if (activeInfo != null && activeInfo.isConnected()
					&& activeInfo.isAvailable()) {
				boolean connected = ethInfo.isConnected();
				boolean available = ethInfo.isAvailable();
				Log.d(TAG, "connected:" + connected);
				Log.d(TAG, "available:" + available);
				if (ethInfo.isConnected() && ethInfo.isAvailable()) {
					icoTitle.setImageResource(R.drawable.ico_title_web);
					transaction.remove(wifiFragment);
					transaction.replace(R.id.wifi_ap_details, ethFragment);
					changeWindowMode(1);
				} else {
					WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
					int wifiState = wifiManager.getWifiState();
					Log.i("Roc", "---- wifiState is " + wifiState);
					if (wifiState != WifiManager.WIFI_STATE_ENABLED
							&& wifiState != WifiManager.WIFI_STATE_ENABLING) {
						wifiManager.setWifiEnabled(true);
					}
				}
			}

			else {
				WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
				int wifiState = wifiManager.getWifiState();
				Log.i("Roc", "==== wifiState is " + wifiState);
				if (wifiState != WifiManager.WIFI_STATE_ENABLED
						&& wifiState != WifiManager.WIFI_STATE_ENABLING) {
					wifiManager.setWifiEnabled(true);
				}
			}

			try {
				transaction.addToBackStack(null);
				transaction.commit();
			} catch (Exception e) {
				// TODO: handle exception
			}

			wifiApDetails.requestFocus();
		}
	}

	@Override
	protected void onPause() {
		if (networkReceiver != null) {
			unregisterReceiver(networkReceiver);
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public boolean onKeyDown(int arg0, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			NetworkSettingsActivity.this.finish();
			return true;
		} else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {
		}
		return super.onKeyDown(arg0, event);
	}
}
